import './index.less'
import { useCountUp } from 'react-countup'
import React, { useEffect, useRef } from 'react'
import { QuestionCircleOutlined } from '@ant-design/icons'
import { Tooltip } from 'antd'

const colorRed = '#FF3B30'
const colorGreen = '#34C759'

const iconRed = '#icon-bailongup'
const iconGreen = '#icon-bailongdown'

const getCompare = (value) => {
  let num = Number(value)
  let obj = {}

  obj.color = num > 0 ? colorRed : colorGreen
  obj.icon = num > 0 ? iconRed : iconGreen

  return obj
}

const DataOverViewBoxItem = ({ item }) => {
  const countRef = useRef(null)

  const handleDecimalsShow = () => {
    if (item.unit === '元' || item.unit === '%') {
      return 2
    } else {
      return 0
    }
  }

  const numberAnimation = useCountUp({
    ref: countRef,
    start: 0,
    end: 0,
    duration: 1.5,
    decimals: handleDecimalsShow()
  })

  const compareRef = useRef(null)
  const compareNumberAnimation = useCountUp({
    ref: compareRef,
    start: 0,
    end: 0,
    duration: 1.5,
    decimals: handleDecimalsShow()
  })


  // 格式化对比数
  const formatCompare = (value) => {
    let num = Number(value)
    let str = ''
    if (num < 0) {
      str = `${num}`.slice(1)
    } else {
      str = `${num}`
    }
    return str
  }

  useEffect(() => {
    numberAnimation.update(item.count)
    compareNumberAnimation.update(formatCompare(item.compare))
  }, [item])

  return (<div className='data_overview_item'>
    <div className='data_overview_item_icon' style={{ background: `url(${item.icon})` }} />
    <div className='data_overview_item_content'>
      <div className='data_overview_item_count' ref={countRef} />
      <div className='data_overview_item_title'>
        <span>{item.name}{item.unit && `(${item.unit})`}</span>
        <Tooltip title={item.tips}>
          <QuestionCircleOutlined />
        </Tooltip>
      </div>
      <div className='data_overview_item_compare'>
        <span>{item.compareText}</span>
        <svg className='icon' aria-hidden='true' style={{ width: '20px', height: '20px' }}>
          <use xlinkHref={getCompare(item.compare).icon}></use>
        </svg>
        <span
          style={{ color: getCompare(item.compare).color, fontFamily: 'DINPro-Medium' }}
          ref={compareRef}>
        </span>
      </div>
    </div>
  </div>)
}
export default DataOverViewBoxItem